// pages/map/map.js
var QQMapWX = require('../../libs/qqmap-wx-jssdk.js');
var qqmapsdk;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    longitude: 103.324520,
    latitude: 23.099994,
    haveSearchResult: false,
    haveSuggestion: false,
    refrashState: false,
    showWindow: false,
    markers: [],
    compName: '',
    mapHeight: '100vh',
    iconBottom: '100rpx',
    backBottom: '0rpx',
    start:{title:'当前位置'},
    end:{title:''}
  },

  //选择起点
  selectPoint(e){
    console.log(e);
    let select=e.currentTarget.id;
    let that=this;
    wx.chooseLocation({
      success: function (res) {
        console.log(res);
        let longitude=res.longitude;
        let latitude=res.latitude;
        that.mapCtx.moveToLocation( {longitude,latitude});

        let markers = that.data.markers;
        let dis = {
          id: markers.length,
          latitude: res.latitude,
          longitude: res.longitude,
          iconPath: "../../images/biaoji.png",
          width: 35,
          height: 35
        }
        markers.push(dis);
        console.log(markers);
        that.setData({
          markers
        })
        
        //坐标到坐标位置文字描述的转换
        qqmapsdk.reverseGeocoder({
          location: {
            latitude: res.latitude,
            longitude: res.longitude
          },
          success: function (res) {
            console.log(res)
            let key=select+'.title';
            that.setData({
              [key]:res.result.formatted_addresses.recommend,
              title: res.result.formatted_addresses.recommend,
              addr: res.result.address
            })
          }
        })
      }
    })
  },

  handleAddressClick() {
    
  },
  //点击位置切换按钮
  changeDir(e){
    console.log("位置切换");
    let startTit=this.data.end.title;
    let endTit=this.data.start.title;
    this.setData({
      ['start.title']:startTit,
      ['end.title']:endTit
    })
  },

  //点击定位按钮
  pointAction: function (e) {
    console.log("回到定位点");
    this.mapCtx.moveToLocation();

    this.mapCtx.getRegion({
      success: function (res) {
        console.log("当前屏幕视野", res);
        let num = (res.northeast.longitude - res.southwest.longitude) * 0.1;
        northLong: res.northeast.longitude - num;
        northLati: res.northeast.latitude - num;
        southLong: res.southwest.longitude + num;
        southLati: res.southwest.latitude + num;
      }
    })
  },
  //上一页
  previousPage(e){
    console.log("点击上一页");
  },

  //点击刷新按钮
  refrashAction: function (e) {
    console.log("刷新");
    let refrashState = !this.data.refrashState
    this.setData({
      refrashState
    })
  },
  //点击查看行程按钮
  travelAction: function (e) {
    console.log("查看行程");
  },
  //点击弹窗中的文字跳转到详情页面
  // compDetailAction

  //点击弹窗中的添加按钮
  addTravel(e) {
    wx.showToast({
      title: '添加到行程',
    })
  },

  //点击关闭弹窗按钮事件
  backWindowAction(e) {
    console.log("点击关闭弹窗");
    this.setData({
      showWindow: false,
      mapHeight: '100vh',
      iconBottom: '100rpx',
      backBottom: '0rpx'
    })
  },
  //点击标记点事件
  markerAction: function (e) {
    console.log("点击标记点");
    let showWindow=!this.data.showWindow;
    let iconBottom=showWindow?'230rpx':'100rpx';
    let backBottom=showWindow?'120rpx':'0rpx';
    this.setData({
      showWindow,
      iconBottom,
      backBottom
    })
  },

  searchPlace: function (e) {
    let searchName = this.data.backfill;
    console.log(searchName, "跳转至搜索页面");
    // let that = this;
    // // 调用接口
    // qqmapsdk.search({
    //   keyword: searchName,
    //   success: function (res) {
    //     console.log(res);
    //     that.setData({
    //       resultList: res.data
    //     })
    //   },
    //   fail: function (res) {
    //     console.log(res);
    //   },
    //   complete: function (res) {
    //     console.log(res);
    //     that.setData({
    //       haveSuggestion: false
    //     })
    //   }
    // })
  },

  closeSuggestion: function () {
    this.setData({
      haveSuggestion: false //选完后
    });
  },

  //数据回填方法
  backfill: function (e) {
    var id = e.currentTarget.id;
    console.log(e);
    for (var i = 0; i < this.data.suggestion.length; i++) {
      if (i == id) {
        let markers = this.data.markers;
        markers[0].latitude = this.data.suggestion[i].latitude;
        markers[0].longitude = this.data.suggestion[i].longitude;
        this.setData({
          markers,
          title: this.data.suggestion[i].title,
          addr: this.data.suggestion[i].addr,
          backfill: this.data.suggestion[i].title,
          haveSuggestion: false, //选完后
          longitude: this.data.suggestion[i].longitude,
          latitude: this.data.suggestion[i].latitude
        });
      }
    }
  },

  //触发关键词输入提示事件
  getsuggest: function (e) {

    this.setData({
      backfill: e.detail.value
    })
    if (e.detail.value === "") {
      this.setData({
        suggestion: [],
        haveSuggestion: false
      })
      return;
    }

    var _this = this;
    //调用关键词提示接口
    qqmapsdk.getSuggestion({
      //获取输入框值并设置keyword参数
      keyword: e.detail.value, //用户输入的关键词，可设置固定值,如keyword:'KFC'
      page_size: 5,
      // region:'北京', //设置城市名，限制关键词所示的地域范围，非必填参数
      success: function (res) { //搜索成功后的回调
        console.log(res);
        var sug = [];
        for (var i = 0; i < res.data.length; i++) {
          sug.push({ // 获取返回结果，放到sug数组中
            title: res.data[i].title,
            id: res.data[i].id,
            addr: res.data[i].address,
            city: res.data[i].city,
            district: res.data[i].district,
            latitude: res.data[i].location.lat,
            longitude: res.data[i].location.lng
          });
        }
        _this.setData({ //设置suggestion属性，将关键词搜索结果以列表形式展示
          suggestion: sug,
          haveSuggestion: true
        });
      },
      fail: function (error) {
        console.error(error);
      },
      complete: function (res) {
        console.log(res);
      }
    });
  },



  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 实例化API核心类
    qqmapsdk = new QQMapWX({
      key: 'GKVBZ-AITRD-ZIP4P-HW2PH-OGTG3-PMFNR'
    });
    //位置获取
    var that = this;
    wx.getLocation({
      type: "gcj02",
      isHighAccuracy: true,
      success: function (res) {
        // console.log(res);
        let markers = [];
        let dis = {
          id: 0,
          latitude: res.latitude,
          longitude: res.longitude,
          iconPath: "../../images/biaoji.png",
          width: 35,
          height: 35
        }
        markers.push(dis);
        that.setData({
          latitude: res.latitude,
          longitude: res.longitude,
          markers
        })
        //坐标到坐标位置文字描述的转换
        qqmapsdk.reverseGeocoder({
          location: {
            latitude: res.latitude,
            longitude: res.longitude
          },
          success: function (res) {
            console.log(res)
            that.setData({
              title: res.result.formatted_addresses.recommend,
              addr: res.result.address
            })
          }
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.mapCtx = wx.createMapContext('myMap');
    this.mapCtx.moveToLocation();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {}
})